package com.daydayup.learn.zikao;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.math.BigDecimal;

/**
 * 设计一个应用程序,单机加或减按钮，将前两个文本框中的整数相加或相减后放入第三个文本框中
 */
public class PlusSub {

    public static void main(String[] args) {
        JButton addBtn = new JButton("加");
        JButton subBtn = new JButton("减");
        JTextField t1 = new JTextField(10);
        JTextField t2 = new JTextField(10);
        JTextField t3 = new JTextField(10);
        JFrame frame = new JFrame("加减计算器");
        Container con = frame.getContentPane();
        frame.setSize(300,80);
        con.setLayout(new GridLayout(1,5));
        con.add(t1);
        con.add(t2);
        con.add(addBtn);
        con.add(subBtn);
        con.add(t3);
        addBtn.addActionListener(e -> {
            try {
                double v1 = Double.parseDouble(t1.getText());
                double v2 = Double.parseDouble(t2.getText());
                t3.setForeground(Color.BLACK);
                t3.setText(BigDecimal.valueOf(v1).add(BigDecimal.valueOf(v2)).toString());
            } catch (Exception ex) {
                t3.setForeground(Color.RED);
                t3.setText("报错了:"+ex.getMessage());
            }
        });
        subBtn.addActionListener(e -> {
            try {
                double v1 = Double.parseDouble(t1.getText());
                double v2 = Double.parseDouble(t2.getText());
                t3.setForeground(Color.BLACK);
                t3.setText(BigDecimal.valueOf(v1).subtract(BigDecimal.valueOf(v2)).toString());
            } catch (Exception ex) {
                t3.setForeground(Color.RED);
                t3.setText("报错了:"+ex.getMessage());
            }
        });
        frame.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {
                System.out.println("windowOpened");
            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing");
                System.exit(1);
            }

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("windowClosed");
            }

            @Override
            public void windowIconified(WindowEvent e) {
                System.out.println("windowIconified");
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                System.out.println("windowDeiconified");
            }

            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("windowActivated");
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
                System.out.println("windowDeactivated");
            }
        });
        frame.setVisible(true);
    }
}
